<template>
	<view class="chat-page" :class="{ 'recording-active': isRecording }">
		<!-- 顶部导航 -->
		<view class="status-bar" :style="{
			height: navHeight + 'px',
			'padding-top': statusBarHeight + 'px',
		}">
			<view class="nav-bar">
				<view class="nav-bar-left">
					<image src="/static/left_arrow.png" class="nav-back-icon" @click="goBack" />
				</view>
				<view class="nav-bar-title">{{ groupTitle }}</view>
				<view v-if="navType == 1" class="nav-bar-right" @click="rightClick">...</view>
				<view v-if="navType == 0" style="color:#100d05;">000</view>
			</view>
		</view>
		<view class="status-height-color" :style="{
			height: navHeight + 'px',
			'padding-top': statusBarHeight + 'px',
		}">
		</view>

		<!-- 聊天内容区域 -->
		<scroll-view class="chat-content" scroll-y :scroll-with-animation="true" :enhanced="true" :bounces="true"
			:show-scrollbar="false" :style="{ height: chatContentHeight }" @scroll="onChatScroll"
			:scroll-into-view="scrollToMessageId">
			<view class="chat-messages">
				<!-- 时间分割线 -->
				<view class="time-divider" v-if="chatMessages.length > 0">
					<text class="time-text">{{
						formatDate(chatMessages[0].timestamp)
					}}</text>
				</view>

				<!-- 消息列表 -->
				<view class="message-item" v-for="(message, index) in chatMessages" :key="message.id || index"
					:id="`msg-${message.id || index}`" :class="{
						'message-mine': message.isMine,
						'message-other': !message.isMine,
					}">
					<!-- 时间分割线 -->
					<view class="time-divider" v-if="shouldShowTimeDivider(index)">
						<text class="time-text">{{ formatDate(message.timestamp) }}</text>
					</view>

					<!-- 消息内容 -->
					<view class="message-content">
						<!-- 头像 -->
						<view class="message-avatar">
							<image :src="getAvatarUrl(message.avatar)" class="avatar-img" mode="aspectFill" />
						</view>

						<!-- 消息气泡 -->
						<view class="message-bubble" :class="{ 'message-image-type': message.type === 'image' }">
							<view class="message-text" v-if="message.type === 'text'">
								{{ message.content }}
							</view>
							<view class="message-emoji" v-else-if="message.type === 'emoji'">
								{{ message.content }}
							</view>
							<view class="message-image" v-else-if="message.type === 'image'">
								<image :src="message.content" class="image-content" mode="aspectFill"
									@click="previewImage(message.content)" />
							</view>
							<view class="message-voice" v-else-if="message.type === 'voice'">
								<view class="voice-content" @click="playVoice(message)">
									<image src="/static/vc.png" class="voice-icon" />
									<!-- <image src="/static/voice.png" class="voice-icon" /> -->
									<!-- <text class="voice-duration">{{ message.duration }}″</text> -->
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 加载更多提示 -->
				<view class="loading-more" v-if="loadingMore">
					<view class="loading-spinner"></view>
					<text class="loading-text">加载中...</text>
				</view>

				<!-- 无消息提示 -->
				<!-- <view class="empty-messages" v-if="chatMessages.length === 0 && !loadingMore">
					<image class="empty-img" src="/static/empty_chat.png" />
					<text class="empty-text">暂无消息</text>
				</view> -->
			</view>
		</scroll-view>

		<!-- 底部输入区域 -->
		<view class="input-area" :class="{ 'ios-safe-area': isIOS, 'android-safe-area': isAndroid }"
			:style="{ bottom: inputAreaBottom }">
			<view class="input-container">
				<!-- 左侧语音按钮 -->
				<view class="input-btn voice-btn" @click="toggleVoiceInput">
					<image :src="isVoiceMode ? '/static/yy-icon.png' : '/static/jianpan.png'" class="btn-icon" />
				</view>

				<!-- 中间输入区域 -->
				<view class="input-center">
					<!-- 文本输入框 -->
					<view class="text-input-wrapper" v-if="!isVoiceMode">
						<input class="text-input" v-model="inputText" :hold-keyboard="true" placeholder="输入消息" :focus="inputFocus"
							@focus="onInputFocus" @blur="onInputBlur" @confirm="sendTextMessage" confirm-type="send"
							:adjust-position="false" :cursor-spacing="20" placeholder-style="color: #ffffff;font-size: 32rpx;"
							placeholder-class="input-placeholder" />
					</view>

					<!-- 语音输入区域 -->
					<view class="voice-input-wrapper" v-if="isVoiceMode">
						<view class="voice-input-btn" @touchstart.stop.prevent="handleRecordStart"
							@touchend.stop.prevent="handleRecordEnd" @touchcancel.stop.prevent="handleRecordEnd"
							@touchmove.stop.prevent="handleRecordMove">
							<!-- 文字和录音条并存，通过CSS控制显示隐藏 -->
							<text class="voice-input-text" :class="{ 'voice-hidden': showRecordingBar }">{{ voiceRecordText }}</text>
							<!-- 录音条始终存在，通过CSS控制显示隐藏 -->
							<view class="recording-bar-outer"
								:class="{ 'recording-visible': showRecordingBar, 'recording-hidden': !showRecordingBar }">
								<view class="recording-bar-inner">
									<view class="recording-bar" :class="{ animating: isRecording }">
										<view v-for="(n, idx) in 13" :key="idx" class="bar" :style="{ '--delay': idx * 0.1 + 's' }">
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 右侧按钮组 -->
				<view class="input-right-buttons">
					<!-- 表情按钮 -->
					<!-- <view class="input-btn emoji-btn" @click="toggleEmojiPanel">
            <image src="/static/image/emoji.png" class="btn-icon" />
          </view> -->

					<!-- 更多功能按钮 -->
					<view class="input-btn" @click="toggleMorePanel">
						<image src="/static/plus-circle.png" class="btn-icon1" />
					</view>
					<view class="input-btn" @touchend.prevent="sendTextMessage">
						<image src="/static/fs-icon.png" class="btn-icon" />
					</view>
				</view>
			</view>

			<!-- 发送按钮 -->
			<!-- <view class="send-btn" v-if="inputText.trim()" @click="sendTextMessage">
        <text class="send-text">发送</text>
      </view> -->
		</view>

		<!-- 表情面板 -->
		<view class="emoji-panel" v-if="showEmojiPanel" :style="{ bottom: emojiPanelBottom }">
			<view class="emoji-content">
				<scroll-view class="emoji-scroll" scroll-y :show-scrollbar="false" :enhanced="true">
					<view class="emoji-grid">
						<view class="emoji-item" v-for="(emoji, index) in emojiList" :key="index" @click="insertEmoji(emoji)">
							{{ emoji }}
						</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 更多功能面板 -->
		<view class="more-panel" v-if="showMorePanel" :style="{ bottom: morePanelBottom }">
			<view class="more-content">
				<view class="more-grid">
					<view class="more-item" @click="selectImage">
						<view class="more-icon-bg">
							<image src="/static/Album.png" class="more-icon" />
						</view>
						<text class="more-text">相册</text>
					</view>
					<view class="more-item" @click="takePhoto">
						<view class="more-icon-bg">
							<image src="/static/Takephoto.png" class="more-icon" />
						</view>
						<text class="more-text">拍照</text>
					</view>
					<view class="more-item" @click="goReport">
						<view class="more-icon-bg">
							<image src="/static/report.png" class="more-icon" />
						</view>
						<text class="more-text">举报</text>
					</view>
					<!-- <view class="more-item" @click="selectFile">
						<image src="/static/image/file.png" class="more-icon" />
						<text class="more-text">文件</text>
					</view> -->
				</view>
			</view>
		</view>

		<!-- 录音提示 -->
		<view class="voice-record-tip" v-if="showVoiceTip">
			<view class="voice-tip-content">
				<text class="voice-tip-text">{{ voiceTipText }}</text>
			</view>
		</view>

		<!-- 群聊操作弹窗 -->
		<tn-popup v-model="showGroupActions" mode="right" width="100%" :borderRadius="20" :maskCloseable="true"
			backgroundColor="#fff" :safeArea="true">
			<view class="group-actions-content">
				<!-- 弹窗头部 -->
				<view class="popup-header" :style="{ paddingTop: popupHeaderPaddingTop }">
					<!-- iOS安全区域适配 -->
					<view class="safe-area-top" v-if="isIOS"></view>

					<!-- 头部内容区域 -->
					<view class="header-content">
						<text class="popup-title">聊天信息</text>
						<view class="close-btn" @click="hideGroupActions">
							<image src="/static/message-close.png" class="close-icon" />
						</view>
					</view>
				</view>

				<!-- 内容区域 -->
				<view class="popup-content">
					<!-- 操作列表 -->
					<view class="actions-list">
						<!-- 群聊成员 -->
						<view class="action-item">
							<view class="action-left">
								<text class="action-text">工作组成员</text>
							</view>
							<text class="member-count">({{ groupMembers.length }})</text>
						</view>

						<!-- 群聊成员列表 -->
						<view class="members-section" v-if="groupMembers.length > 0">
							<view class="members-grid">
								<view class="member-item" v-for="member in groupMembers" :key="member.id">
									<view class="member-avatar">
										<image :src="getAvatarUrl(member.avatar)" class="avatar-img" mode="aspectFill" />
									</view>
									<text class="member-name">{{ member.nickname }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 底部按钮区域 -->
				<view class="bottom-buttons">
					<!-- 动态按钮：根据用户身份显示退出或解散 -->
					<view class="action-button exit-button" @click="onGroupAction">
						<text class="button-text">{{ getButtonText() }}</text>
					</view>
				</view>
			</view>
		</tn-popup>

		<!-- 添加图片预览组件 -->
		<view class="image-preview" v-if="showImagePreview" @click="closeImagePreview">
			<image :src="previewImageUrl" class="preview-image" mode="aspectFit" />
		</view>
	</view>
</template>

<script>
import { pathToBase64 } from 'mmmm-image-tools'
export default {
	name: "groupChat",
	data() {
		return {
			navHeight: "", // 整体顶部导航栏的高度
			statusBarHeight: "", // 状态栏高度
			groupid: "", // 群聊id
			groupTitle: "", // 群聊标题
			master_id: "", // 群主id
			friendId: "", // 好友id
			navType: "", // 是否显示导航栏右边三个点

			// 系统信息
			systemInfo: {}, // 系统信息
			isIOS: false, // 是否为iOS系统
			isAndroid: false, // 是否为Android系统
			safeAreaBottom: 0, // 底部安全区域高度

			// 聊天相关
			chatMessages: [], // 聊天消息列表
			loadingMore: false, // 是否正在加载更多
			scrollToMessageId: "", // 滚动到指定消息

			// 输入相关
			inputText: "", // 输入框文本
			inputFocus: false, // 输入框是否聚焦
			isVoiceMode: false, // 是否为语音输入模式
			voiceRecordText: "按住说话", // 语音按钮文本

			// 面板显示
			showEmojiPanel: false, // 是否显示表情面板
			showMorePanel: false, // 是否显示更多功能面板
			showVoiceTip: false, // 是否显示录音提示
			voiceTipText: "手指上滑，取消发送", // 录音提示文本
			showGroupActions: false, // 是否显示群聊操作弹窗

			// 新增：显式控制录音条显示
			showRecordingBar: false,

			// 群聊成员数据
			groupMembers: [], // 群聊成员列表
			userid: "", // 当前用户ID
			// 软键盘监听相关
			keyboardHeight: 0, // 键盘高度
			isKeyboardShow: false, // 键盘是否显示
			originalWindowHeight: 0, // 原始窗口高度
			currentWindowHeight: 0, // 当前窗口高度
			scrollViewHeight: 0, // scroll-view的实际高度

			// 录音相关
			isRecording: false, // 是否正在录音
			recordStartTime: 0, // 录音开始时间
			recordDuration: 0, // 录音时长
			startY: 0, // 触摸起始Y坐标
			willCancelRecord: false, // 是否将要取消录音
			recordingTimer: null, // 录音安全定时器

			// 表情列表
			emojiList: [
				"😀",
				"😃",
				"😄",
				"😁",
				"😆",
				"😅",
				"😂",
				"🤣",
				"😊",
				"😇",
				"🙂",
				"🙃",
				"😉",
				"😌",
				"😍",
				"🥰",
				"😘",
				"😗",
				"😙",
				"😚",
				"😋",
				"😛",
				"😝",
				"😜",
				"🤪",
				"🤨",
				"🧐",
				"🤓",
				"😎",
				"🤩",
				"🥳",
				"😏",
				"😒",
				"😞",
				"😔",
				"😟",
				"😕",
				"🙁",
				"☹️",
				"😣",
				"😖",
				"😫",
				"😩",
				"🥺",
				"😢",
				"😭",
				"😤",
				"😠",
				"😡",
				"🤬",
				"🤯",
				"😳",
				"🥵",
				"🥶",
				"😱",
				"😨",
				"😰",
				"😥",
				"😓",
				"🤗",
				"🤔",
				"🤭",
				"🤫",
				"🤥",
				"😶",
				"😐",
				"😑",
				"😯",
				"😦",
				"😧",
				"😮",
				"😲",
				"🥱",
				"😴",
				"🤤",
				"😪",
				"😵",
				"🤐",
				"🥴",
				"🤢",
				"🤮",
				"🤧",
				"😷",
				"🤒",
				"🤕",
				"🤑",
				"🤠",
				"💩",
				"👻",
				"💀",
				"☠️",
				"👽",
				"👾",
				"🤖",
				"😈",
				"👿",
				"👹",
				"👺",
				"🤡",
				"👺",
				"👻",
				"💀",
				"☠️",
				"👽",
				"👾",
				"🤖",
				"😈",
				"👿",
				"👹",
				"👺",
				"🤡",
				"👺",
				"👶",
				"👧",
				"🧒",
				"👦",
				"👩",
				"🧑",
				"👨",
				"👵",
				"🧓",
				"👴",
				"👮‍♀️",
				"👮‍♂️",
				"🕵️‍♀️",
				"🕵️‍♂️",
				"💂‍♀️",
				"💂‍♂️",
				"👷‍♀️",
				"👷‍♂️",
				"🤴",
				"👸",
				"👳‍♀️",
				"👳‍♂️",
				"👲",
				"🧕‍♀️",
				"🤵‍♀️",
				"🤵‍♂️",
				"��‍♀️",
				"👰‍♂️",
				"🤰",
				"🤱",
				"👼",
				"🎅",
				"🤶",
				"🧙‍♀️",
				"🧙‍♂️",
				"🧚‍♀️",
				"🧚‍♂️",
				"🧛‍♀️",
				"🧛‍♂️",
				"🧜‍♀️",
				"🧜‍♂️",
				"🧝‍♀️",
				"🧝‍♂️",
				"🧞‍♀️",
				"🧞‍♂️",
				"🧟‍♀️",
				"��‍♂️",
			],

			// 添加新的数据属性
			messageType: {
				TEXT: 1,
				IMAGE: 2,
				AUDIO: 3
			},

			// 添加录音相关属性
			recorderManager: null, // 录音管理器
			currentAudioPath: null, // 当前录音文件路径
			// 音频播放
			innerAudioContext: null, // 全局音频播放实例
			currentlyPlayingId: null, // 当前播放中的消息ID
			userHead: "", // 当前用户头像

			// 图片预览相关
			showImagePreview: false,
			previewImageUrl: "",

			// 轮询相关
			pollTimer: null, // 轮询定时器
			pollInterval: 1500, // 轮询间隔，1.5秒
			lastMessageId: null, // 最后一条消息的ID，用于判断是否有新消息
		}
	},

	computed: {
		// 聊天内容区域高度
		chatContentHeight() {
			const {
				statusBarHeight,
				system
			} = uni.getSystemInfoSync()
			const navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48)
			const inputHeight = 120 // 输入区域高度
			const emojiHeight = this.showEmojiPanel ? 400 : 0 // 表情面板高度
			const moreHeight = this.showMorePanel ? 200 : 0 // 更多功能面板高度
			return `calc(100vh - ${navHeight}px - ${inputHeight}rpx - ${emojiHeight}rpx - ${moreHeight}rpx`
		},

		// 输入区域底部位置
		inputAreaBottom() {
			const emojiHeight = this.showEmojiPanel ? 400 : 0
			const moreHeight = this.showMorePanel ? 200 : 0
			return `${emojiHeight + moreHeight}rpx`
		},

		// 表情面板底部位置
		emojiPanelBottom() {
			const moreHeight = this.showMorePanel ? 200 : 0
			return `${moreHeight}rpx`
		},

		// 更多功能面板底部位置
		morePanelBottom() {
			return "0rpx"
		},

		// 弹窗头部顶部内距
		popupHeaderPaddingTop() {
			if (this.isIOS) {
				// iOS设备，考虑刘海屏和灵动岛
				// 使用系统状态栏高度 + 额外安全距离
				const extraPadding = this.statusBarHeight > 44 ? 30 : 20 // 刘海屏设备需要更多空间
				return `${this.statusBarHeight + extraPadding}rpx`
			} else {
				// Android设备
				return "40rpx"
			}
		},
	},

	onLoad: async function (options) {
		// 获取系统信息
		this.getSystemInfo()
		let {
			statusBarHeight,
			system
		} = uni.getSystemInfoSync()
		this.statusBarHeight = statusBarHeight
		this.navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48)

		// 先获取当前用户ID（本地同步）
		this.getCurrentUserId()

		// 解析参数，优先直接使用传入的 groupid
		if (options && options.groupid) {
			this.groupid = options.groupid
		}
		if (options && options.friendId) {
			this.friendId = options.friendId
			// 若未携带 groupid，则通过检测接口获取
			if (!this.groupid) {
				await this.checkGroup()
			}
		}

		// 获取对应群聊信息（需要 groupid）
		this.loadGroupInfo()
		// 加载聊天记录（需要 userid 与 groupid）
		await this.loadChatMessages()
		// 获取初始窗口高度
		this.getInitialWindowHeight()
		// 监听软键盘弹出
		this.addKeyboardListener()

		// 初始化录音管理器
		this.initRecorderManager()
		// 延迟初始化音频播放器，避免在页面加载时立即创建
		setTimeout(() => {
			this.initAudioPlayer()
		}, 1000)
	},
	onShow() {
		// 页面显示时，确保输入框不被键盘遮挡
		this.adjustInputPosition()
		// 监听软键盘弹出
		this.addKeyboardListener()
		// 启动消息轮询
		this.startMessagePolling()

		// 增加：确保录音状态被重置（特别是Android）
		this.isRecording = false
		this.showRecordingBar = false
		this.showVoiceTip = false

		// 设置全局事件监听
		uni.$on('record-ended', () => {
			// 收到录音结束事件，强制隐藏录音条
			this.isRecording = false;
			this.showRecordingBar = false;
			this.$forceUpdate();
		});
	},
	onHide() {
		this.removeKeyboardListener()
		// 页面隐藏时停止播放
		if (this.innerAudioContext) {
			this.innerAudioContext.stop()
			this.currentlyPlayingId = null
		}

		// 确保在离开页面时停止录音
		this.resetRecordingState()

		// 停止消息轮询
		this.stopMessagePolling()

		// 增加：清理事件监听
		uni.$off('record-ended');
	},
	onUnload() {
		// 释放音频实例
		if (this.innerAudioContext) {
			this.innerAudioContext.stop()
			this.innerAudioContext.destroy()
			this.innerAudioContext = null
		}

		// 确保在卸载页面时停止录音并重置所有状态
		this.resetRecordingState()

		// 停止消息轮询
		this.stopMessagePolling()

		// 增加：清理事件监听
		uni.$off('record-ended');
	},

	methods: {
		// 获取初始窗口高度
		getInitialWindowHeight() {
			const systemInfo = uni.getSystemInfoSync()
			this.originalWindowHeight = systemInfo.windowHeight
			this.currentWindowHeight = systemInfo.windowHeight
		},

		// 添加软键盘监听
		addKeyboardListener() {
			this.removeKeyboardListener()
			// 监听键盘高度变化
			uni.onKeyboardHeightChange((res) => {
				// 针对ios，默认消息滚动做的处理不可删除
				if (this.isIOS) {
					if (this.chatMessages && this.chatMessages.length) {
						const lastMessage = this.chatMessages[0]
						this.scrollToMessageId = `msg-${lastMessage.id}`
					}
				}

				this.keyboardHeight = res.height
				if (res.height > 0) {
					// 键盘弹出
					this.onKeyboardShow(res.height)
				} else {
					this.keyboardHeight = 0
					this.scrollToMessageId = ""
					// 键盘收起
					this.onKeyboardHide()
				}
			})
		},

		// 移除软键盘监听
		removeKeyboardListener() {
			try {
				uni.offKeyboardHeightChange()
			} catch (error) {
			}
		},

		// 键盘弹出处理
		onKeyboardShow(height) {
			this.isKeyboardShow = true
			// ios 必须监听500以上，避免页面高度变化期间就进行滚动，会导致消息滚动不了
			const Time = this.isIOS ? 500 : 150
			// 隐藏表情和更多功能面板
			this.hidePanels()

			// 延迟执行滚动，确保页面高度调整完成
			this.$nextTick(() => {
				setTimeout(() => {
					this.scrollToBottomWithKeyboard()
				}, Time) // 增加延迟时间，确保页面完全调整
			})
		},

		// 键盘收起处理
		onKeyboardHide() {
			this.isKeyboardShow = false
			this.scrollToMessageId = ""
			// 键盘收起后，重新调整滚动位置
			this.$nextTick(() => {
				setTimeout(() => {
					this.scrollToBottom()
				}, 100)
			})
		},

		// 键盘弹出时的滚动到底部方法
		scrollToBottomWithKeyboard() {
			if (this.chatMessages.length === 0) return

			const lastMessage = this.chatMessages[this.chatMessages.length - 1]
			// 方法2: 同时使用scroll-top设置一个很大的值确保滚动到底部
			this.$nextTick(() => {
				setTimeout(() => {
					this.scrollToMessageId = `msg-${lastMessage.id}`
				}, 150)

			})
		},
		// 获取系统信息
		getSystemInfo() {
			try {
				const systemInfo = uni.getSystemInfoSync()
				this.systemInfo = systemInfo

				// 判断系统类型
				this.isIOS =
					systemInfo.platform === "ios" ||
					systemInfo.system.toLowerCase().includes("ios")
				this.isAndroid =
					systemInfo.platform === "android" ||
					systemInfo.system.toLowerCase().includes("android")

				// 获取底部安全区域高度
				if (this.isIOS && systemInfo.safeArea) {
					const screenHeight = systemInfo.screenHeight
					const safeAreaBottom = systemInfo.safeArea.bottom
					this.safeAreaBottom = screenHeight - safeAreaBottom
				} else {
					this.safeAreaBottom = 0
				}

			} catch (error) {
				console.error("获取系统信息失败:", error)
				// 默认设置为Android
				this.isAndroid = true
				this.isIOS = false
				this.safeAreaBottom = 0
			}
		},

		// 返回上一页
		goBack() {
			uni.navigateBack()
		},

		// 点击右边三个小点
		rightClick() {
			this.showGroupActions = true
		},

		// 隐藏群聊操作弹窗
		hideGroupActions() {
			this.showGroupActions = false
		},

		// 加载群聊信息
		async loadGroupInfo() {
			try {
				// 调用接口获取群聊信息
				const response = await this.$Request.postApi("/bot/api/agentcgetgroupinfo", { id: this.groupid, userid: this.userid })
				if (response.status === 1) {
					this.groupTitle = response.data.name;
					this.master_id = response.data.master_id;
					this.navType = response.data.type;
					// 获取群聊成员列表
					if (response.data.userlist && Array.isArray(response.data.userlist)) {
						this.groupMembers = response.data.userlist.map((member, index) => ({
							id: index,
							avatar: member.user_head,
							nickname: member.nickname || "未知用户",
						}))
					}
				}
			} catch (error) {
				console.error("获取群聊信息失败:", error)
			}
		},

		// 加载聊天记录
		async loadChatMessages() {
			try {
				this.loadingMore = true

				// 空值保护
				if (!this.userid || !this.groupid) {
					console.warn('缺少必要参数，无法拉取聊天记录:', { userid: this.userid, groupid: this.groupid })
					this.loadingMore = false
					return
				}

				// 调用接口获取聊天记录
				const response = await this.$Request.postApi('/bot/api/agentcgetimmessage', {
					userid: this.userid,
					groupid: this.groupid
				})

				if (response && response.status === 1 && Array.isArray(response.data)) {
					// 将接口数据映射到现有消息结构
					const mapped = response.data
						.sort((a, b) => (this.normalizeTimestamp(a.create_time) - this.normalizeTimestamp(b.create_time)))
						.map(item => this.formatMessageFromApi(item))
					this.chatMessages = mapped
					this.$nextTick(() => {
						this.scrollToBottom()
					})

					// 保存最后一条消息ID
					if (mapped.length > 0) {
						this.lastMessageId = mapped[mapped.length - 1].id;
					}

					// 加载完初始消息后启动轮询
					this.startMessagePolling();
				} else {
					this.chatMessages = []
				}

				this.loadingMore = false
			} catch (error) {
				console.error("加载聊天记录失败:", error)
				this.loadingMore = false
			}
		},

		// 添加测试消息
		addTestMessages() {
			const testMessages = [{
				id: 1,
				type: "text",
				content: "哈哈哈",
				isMine: false,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 180000, // 3分钟前
			},
			{
				id: 2,
				type: "emoji",
				content: "😛",
				isMine: true,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 120000, // 2分钟前
			},
			{
				id: 3,
				type: "emoji",
				content: "😐",
				isMine: true,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 120000,
			},
			{
				id: 4,
				type: "emoji",
				content: "😮",
				isMine: true,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 120000,
			},
			{
				id: 5,
				type: "text",
				content: "你好呀",
				isMine: false,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 60000, // 1分钟前
			},
			{
				id: 6,
				type: "text",
				content: "你好呀",
				isMine: true,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 30000, // 30秒前
			},
			{
				id: 7,
				type: "text",
				content: "你好呀",
				isMine: true,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 30000, // 30秒前
			},
			{
				id: 8,
				type: "text",
				content: "你好呀",
				isMine: true,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 30000, // 30秒前
			},
			{
				id: 9,
				type: "text",
				content: "你好呀",
				isMine: false,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 30000, // 30秒前
			},
			{
				id: 10,
				type: "text",
				content: "你好呀",
				isMine: false,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 30000, // 30秒前
			},
			{
				id: 11,
				type: "text",
				content: "你好呀",
				isMine: false,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 30000, // 30秒前
			},
			{
				id: 12,
				type: "text",
				content: "你好呀",
				isMine: false,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 30000, // 30秒前
			},
			{
				id: 13,
				type: "text",
				content: "你好呀",
				isMine: true,
				avatar: "/static/default_avatar.jpg",
				timestamp: Date.now() - 30000, // 30秒前
			},
			]

			this.chatMessages = testMessages
			this.scrollToBottom()
		},

		// 格式化消息
		formatMessage(messageData) {
			return {
				id: messageData.id,
				type: messageData.type || "text",
				content: messageData.content || "",
				isMine: messageData.isMine || false,
				avatar: messageData.avatar || "/static/default_avatar.jpg",
				timestamp: messageData.timestamp || Date.now(),
				duration: messageData.duration || 0,
			}
		},

		// 将接口消息转为前端展示结构
		formatMessageFromApi(apiItem) {
			// 增加详细日志，帮助调试语音消息处理
			if (apiItem.type === 3) {
			}

			const msgType = apiItem.type === 2 ? 'image' : (apiItem.type === 3 ? 'voice' : 'text')
			const isMineMsg = apiItem && String(apiItem.from_id) === String(this.userid)
			const avatarUrl = (apiItem && apiItem.userinfo && apiItem.userinfo.user_head) ? this.getAvatarUrl(apiItem.userinfo.user_head) : '/static/default_avatar.jpg'
			const ts = this.normalizeTimestamp(apiItem && apiItem.create_time)

			// 为语音消息设置默认持续时间（如果后端未返回）
			let duration = apiItem.duration || 0
			if (msgType === 'voice' && duration === 0) {
				// 通常语音消息至少持续1秒
				duration = 1
			}

			const base = {
				id: apiItem.id,
				type: msgType,
				isMine: isMineMsg,
				avatar: avatarUrl,
				timestamp: ts,
				duration: duration
			}

			if (msgType === 'voice') {
				// 确保语音消息有正确的 audioPath 和空的 content
				const result = {
					...base,
					content: '',
					audioPath: apiItem.content
				}
				return result
			} else {
				return { ...base, content: apiItem.content }
			}
		},

		// 统一时间戳（秒/毫秒）
		normalizeTimestamp(value) {
			if (!value) return Date.now()
			const num = Number(value)
			// 小于10^12则视为秒
			return num < 1e12 ? num * 1000 : num
		},

		// 获取当前用户ID
		getCurrentUserId() {
			try {
				// 从本地存储获取用户ID
				const userInfo = uni.getStorageSync("userInfo")
				if (userInfo && userInfo.id) {
					this.userid = userInfo.id
					this.userHead = userInfo.user_head || userInfo.avatar || ""
				} else {
					// 如果没有本地存储，尝试从其他方式获取
					// 这里可以根据实际项目情况调整
					console.warn("未找到用户ID，请检查登录状态")
				}
			} catch (error) {
				console.error("获取用户ID失败:", error)
			}
		},

		// 获取按钮文本
		getButtonText() {
			if (this.master_id && this.userid && this.master_id == this.userid) {
				return "解散工作组"
			} else {
				return "退出工作组"
			}
		},

		// 获取头像URL
		getAvatarUrl(avatar) {
			if (!avatar) {
				return "/static/default_avatar.jpg"
			}
			if (/^https?:\/\//.test(avatar)) return avatar
			return "https://tob.cycyai.com/" + avatar.replace(/^\/+/, "")
		},

		// 格式化日期
		formatDate(timestamp) {
			if (!timestamp) return ""

			const date = new Date(timestamp)
			const now = new Date()
			const diff = now - date
			const oneDay = 24 * 60 * 60 * 1000

			if (diff < oneDay) {
				// 今天
				const hours = date.getHours().toString().padStart(2, "0")
				const minutes = date.getMinutes().toString().padStart(2, "0")
				return `${hours}:${minutes}`
			} else if (diff < 2 * oneDay) {
				// 昨天
				const hours = date.getHours().toString().padStart(2, "0")
				const minutes = date.getMinutes().toString().padStart(2, "0")
				return `昨天 ${hours}:${minutes}`
			} else {
				// 其他日期
				const month = (date.getMonth() + 1).toString()
				const day = date.getDate().toString()
				const hours = date.getHours().toString().padStart(2, "0")
				const minutes = date.getMinutes().toString().padStart(2, "0")
				return `${month}月${day}日 ${hours}:${minutes}`
			}
		},

		// 判断是否显示时间分割线
		shouldShowTimeDivider(index) {
			if (index === 0) return false

			const currentMsg = this.chatMessages[index]
			const prevMsg = this.chatMessages[index - 1]

			if (!currentMsg || !prevMsg) return false

			const timeDiff = Math.abs(currentMsg.timestamp - prevMsg.timestamp)
			return timeDiff > 5 * 60 * 1000 // 5分钟间隔显示时间
		},

		// 聊天区域滚动
		onChatScroll(e) {
			this.scrollToMessageId = ""
		},

		// 输入框聚焦
		onInputFocus() {
			this.inputFocus = true
			this.hidePanels()

			// 如果键盘已经显示，立即滚动到底部
			if (this.isKeyboardShow) {
				this.$nextTick(() => {
					this.scrollToBottomWithKeyboard()
				})
			}
		},

		// 输入框失焦
		onInputBlur() {
			this.inputFocus = false
		},

		// 调整输入框位置
		adjustInputPosition() {
			// 如果键盘已经弹出，滚动到底部
			if (this.isKeyboardShow) {
				this.$nextTick(() => {
					this.scrollToBottomWithKeyboard()
				})
			}
		},

		// 切换语音输入模式
		toggleVoiceInput() {
			this.isVoiceMode = !this.isVoiceMode
			this.hidePanels()

			if (this.isVoiceMode) {
				this.voiceRecordText = "按住说话"
			} else {
				this.voiceRecordText = "按住说话"
			}
		},

		// 开始语音录制（参考 map.vue 实现）
		handleRecordStart(e) {
			// console.log('开始录音被调用', { platform: this.isAndroid ? 'Android' : 'iOS' })

			// 设置录音状态
			this.isRecording = true
			this.showRecordingBar = true // 明确控制录音条显示
			this.recordStartTime = Date.now()
			this.showVoiceTip = true
			this.voiceTipText = "手指上滑，取消发送"
			this.currentAudioPath = null // 重置音频路径
			this.willCancelRecord = false // 确保重置取消状态

			// 记录触摸起始位置（兼容 touch 和 mouse）
			if (e && e.touches && e.touches.length) {
				this.startY = e.touches[0].clientY
			} else if (e && typeof e.clientY === "number") {
				this.startY = e.clientY
			} else {
				this.startY = 0
			}

			// 禁用页面滚动
			this.disablePageScroll()

			// 设置安全定时器：最长录音时间60秒，超时自动停止
			this.clearRecordingTimer() // 清除可能存在的旧定时器
			this.recordingTimer = setTimeout(() => {
				if (this.isRecording) {
					// console.log('录音安全定时器触发：超时自动停止')
					this.handleRecordEnd()
				}
			}, 60000) // 60秒安全限制

			// #ifdef APP-PLUS
			// 开始录音
			if (this.recorderManager) {
				try {
					this.recorderManager.start({
						format: 'mp3',
						sampleRate: 16000,
						numberOfChannels: 1,
						encodeBitRate: 96000,
						frameSize: 50
					})
					// console.log('录音开始成功')
				} catch (error) {
					console.error('录音开始失败:', error)
					// 重置状态
					this.isRecording = false
					this.showRecordingBar = false // 明确隐藏录音条
					this.showVoiceTip = false
					uni.showToast({
						title: '录音启动失败',
						icon: 'none'
					})
				}
			} else {
				console.error('录音管理器不存在')
				this.isRecording = false
				this.showRecordingBar = false // 明确隐藏录音条
				this.showVoiceTip = false
			}
			// #endif

			// #ifndef APP-PLUS
			console.warn('当前环境不支持录音')
			this.isRecording = false
			this.showRecordingBar = false // 明确隐藏录音条
			this.showVoiceTip = false
			// #endif

			// 强制更新UI
			this.$forceUpdate()
		},

		// 停止语音录制（参考 map.vue 实现）
		handleRecordEnd() {
			// console.log('停止录音被调用', { isRecording: this.isRecording })

			// 清除安全定时器
			this.clearRecordingTimer()

			// 防止重复调用或状态不一致
			if (!this.isRecording) {
				// console.log('录音状态检查：当前未在录音，直接返回')
				return
			}

			// 强制立即隐藏录音提示
			this.showVoiceTip = false
			this.voiceTipText = "手指上滑，取消发送"

			// 1. 立即隐藏录音条 - 先设置状态
			this.showRecordingBar = false
			this.isRecording = false
			this.$forceUpdate() // 强制视图更新

			// 2. 再次尝试隐藏 (Android兼容性处理)
			setTimeout(() => {
				try {
					// 使用uni选择器代替document
					const query = uni.createSelectorQuery();
					query.selectAll('.recording-bar-outer').fields({
						rect: true,
						size: true
					}, data => {
						// console.log('找到录音条元素:', data);
					}).exec();
				} catch (e) {
					// console.error('选择器API失败:', e);
				}

				// 强制再次设置状态并更新
				this.showRecordingBar = false
				this.isRecording = false
				this.$forceUpdate()

				// 3. 再延时，做最后保险
				setTimeout(() => {
					this.showRecordingBar = false
					this.isRecording = false
					this.$forceUpdate()
				}, 50);

			}, 10);

			// 恢复页面滚动
			this.enablePageScroll()

			// 检查是否要取消录音
			if (this.willCancelRecord) {
				// console.log("取消录音")
				this.willCancelRecord = false
				// #ifdef APP-PLUS
				if (this.recorderManager) {
					try {
						this.recorderManager.stop()
						// console.log('录音取消成功')
					} catch (error) {
						console.error('录音取消失败:', error)
					}
				}
				// #endif
				return
			}

			// #ifdef APP-PLUS
			// 停止录音
			if (this.recorderManager) {
				try {
					this.recorderManager.stop()
					// console.log('录音停止成功')
				} catch (error) {
					console.error('录音停止失败:', error)
				}
			}
			// #endif

			// 计算录音时长
			this.recordDuration = Math.round(
				(Date.now() - this.recordStartTime) / 1000
			)

			if (this.recordDuration > 0) {
				// 延迟发送语音消息，等待录音文件生成完成
				setTimeout(() => {
					this.sendVoiceMessage(this.recordDuration)
				}, 500)
			}
		},

		// 取消语音录制（兼容性方法，现在由 handleRecordEnd 处理）
		cancelVoiceRecord(e) {
			// console.log('取消录音被调用（兼容性方法）')
			this.handleRecordEnd()
		},

		// 触摸移动检测（用于上滑取消发送，参考 map.vue 实现）
		handleRecordMove(e) {
			if (!this.isRecording) return

			// console.log('触摸移动事件')

			// 兼容 touch 和 mouse
			let currentY = 0
			if (e && e.touches && e.touches.length) {
				currentY = e.touches[0].clientY
			} else if (e && typeof e.clientY === "number") {
				currentY = e.clientY
			}

			// 如果上滑距离超过阈值，显示取消发送提示
			if (this.startY && currentY && this.startY - currentY > 50) {
				this.voiceTipText = "松开手指，取消发送"
				this.willCancelRecord = true
			} else {
				this.voiceTipText = "手指上滑，取消发送"
				this.willCancelRecord = false
			}
		},

		// 兼容性方法：旧的 startVoiceRecord 调用
		startVoiceRecord(e) {
			// console.log('startVoiceRecord 被调用（兼容性方法）')
			this.handleRecordStart(e)
		},

		// 兼容性方法：旧的 stopVoiceRecord 调用
		stopVoiceRecord(e) {
			// console.log('stopVoiceRecord 被调用（兼容性方法）')
			this.handleRecordEnd(e)
		},

		// 发送语音消息
		sendVoiceMessage(duration) {
			const voiceMessage = {
				id: Date.now(),
				type: "voice",
				content: "",
				isMine: true,
				avatar: this.userHead ? this.userHead : "/static/default_avatar.png",
				timestamp: Date.now(),
				duration: duration,
				// 使用当前录音文件路径
				audioPath: this.currentAudioPath
			}

			this.chatMessages.push(voiceMessage)

			// 根据键盘状态选择滚动方法
			if (this.isKeyboardShow) {
				this.scrollToBottomWithKeyboard()
			} else {
				this.scrollToBottom()
			}

			// 发送语音消息到服务器
			this.sendMessageToServer(voiceMessage)
		},

		// 发送文本消息
		sendTextMessage() {
			if (!this.inputText.trim()) return
			this.inputFocus = true;
			const textMessage = {
				id: Date.now(),
				type: "text",
				content: this.inputText.trim(),
				isMine: true,
				avatar: this.userHead ? this.userHead : "/static/default_avatar.png",
				timestamp: Date.now(),
			}

			this.chatMessages.push(textMessage)
			this.inputText = ""

			// 根据键盘状态选择滚动方法
			if (this.isKeyboardShow) {
				this.scrollToBottomWithKeyboard()
			} else {
				this.scrollToBottom()
			}

			// 调用接口发送消息到服务器
			this.sendMessageToServer(textMessage)
		},

		// 发送消息到服务器
		async sendMessageToServer(message) {
			try {
				// 构建请求参数
				const requestData = {
					userid: this.userid,
					groupid: this.groupid,
					type: this.messageType.TEXT,
					content: message.content
				}

				// 根据消息类型设置参数
				if (message.type === 'image') {
					requestData.type = this.messageType.IMAGE
					requestData.content = '图片消息'
					// 图片文件转换为base64
					try {
						const base64 = await pathToBase64(message.content)
						requestData.file = base64
					} catch (error) {
						console.error('图片转base64失败:', error)
						uni.showToast({
							title: '图片处理失败',
							icon: 'none'
						})
						return
					}
				} else if (message.type === 'voice') {
					requestData.type = this.messageType.AUDIO
					requestData.content = '语音消息'

					// 检查是否有音频文件路径
					if (!message.audioPath) {
						console.error('语音消息缺少音频文件路径')
						uni.showToast({
							title: '语音文件获取失败',
							icon: 'none'
						})
						return
					}

					// 语音文件转换为base64
					try {
						const base64 = await pathToBase64(message.audioPath)
						requestData.file = base64
						// console.log('音频转base64成功，长度:', base64.length)
					} catch (error) {
						console.error('音频转base64失败:', error)
						uni.showToast({
							title: '音频处理失败',
							icon: 'none'
						})
						return
					}
				}

				// console.log('发送消息请求参数:', requestData)

				// 调用发送消息接口
				const response = await this.$Request.postApi("/bot/api/agentcsetimmessage", requestData)

				if (response.status === 1) {
					// console.log("消息发送成功:", response.message)
					// 可以在这里更新消息状态，比如标记为已发送
					message.status = 'sent'
				} else {
					console.error("消息发送失败:", response.message)
					uni.showToast({
						title: response.message || '发送失败',
						icon: 'none'
					})
					// 可以在这里标记消息发送失败
					message.status = 'failed'
				}
			} catch (error) {
				console.error("发送消息失败:", error)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
				// 标记消息发送失败
				message.status = 'failed'
			}
		},

		// 普通滚动到底部方法
		scrollToBottom() {
			if (this.chatMessages.length === 0) return

			this.$nextTick(() => {
				const lastMessage = this.chatMessages[this.chatMessages.length - 1]
				this.scrollToMessageId = `msg-${lastMessage.id}`
			})
		},

		// 切换表情面板
		toggleEmojiPanel() {
			this.showEmojiPanel = !this.showEmojiPanel
			this.showMorePanel = false
			this.inputFocus = false
		},

		// 切换更多功能面板
		toggleMorePanel() {
			this.showMorePanel = !this.showMorePanel
			this.showEmojiPanel = false
			this.inputFocus = false
		},

		// 隐藏所有面板
		hidePanels() {
			this.showEmojiPanel = false
			this.showMorePanel = false
		},

		// 插入表情
		insertEmoji(emoji) {
			this.inputText += emoji
		},

		// 选择图片
		selectImage() {
			uni.chooseImage({
				count: 1,
				sizeType: ["compressed"],
				sourceType: ["album"],
				success: (res) => {
					const imageMessage = {
						id: Date.now(),
						type: "image",
						content: res.tempFilePaths[0],
						isMine: true,
						avatar: this.userHead ? this.userHead : "/static/default_avatar.png",
						timestamp: Date.now(),
					}

					this.chatMessages.push(imageMessage)

					// 根据键盘状态选择滚动方法
					if (this.isKeyboardShow) {
						this.scrollToBottomWithKeyboard()
					} else {
						this.scrollToBottom()
					}

					this.hidePanels()

					// 发送图片消息到服务器
					this.sendMessageToServer(imageMessage)
				},
			})
		},

		// 拍照
		takePhoto() {
			uni.chooseImage({
				count: 1,
				sizeType: ["compressed"],
				sourceType: ["camera"],
				success: (res) => {
					const imageMessage = {
						id: Date.now(),
						type: "image",
						content: res.tempFilePaths[0],
						isMine: true,
						avatar: this.userHead ? this.userHead : "/static/default_avatar.png",
						timestamp: Date.now(),
					}

					this.chatMessages.push(imageMessage)

					// 根据键盘状态选择滚动方法
					if (this.isKeyboardShow) {
						this.scrollToBottomWithKeyboard()
					} else {
						this.scrollToBottom()
					}

					this.hidePanels()

					// 发送图片消息到服务器
					this.sendMessageToServer(imageMessage)
				},
			})
		},
		// 举报
		goReport() {
			uni.navigateTo({
				url: "/minePages/report"
			})
		},
		// 选择文件
		selectFile() {
			// 这里可以实现文件选择功能
			uni.showToast({
				title: "文件功能开发中",
				icon: "none",
			})
		},


		// 查看群聊成员
		onGroupMembers() {
			// 群聊成员已经在弹窗中显示，无需额外操作
			// console.log("群聊成员数量:", this.groupMembers.length)
		},

		// 群组操作（退出或解散）
		onGroupAction() {
			const isMaster =
				this.master_id && this.userid && this.master_id == this.userid
			const actionText = isMaster ? "解散" : "退出"
			const actionContent = isMaster ?
				"确定要解散该工作组吗？解散后无法恢复！" :
				"确定要退出该工作组吗？"


			this.hideGroupActions()
			uni.showModal({
				title: `确认${actionText}`,
				content: actionContent,
				confirmText: actionText,
				confirmColor: "#ff4757",
				success: (res) => {
					if (res.confirm) {
						if (isMaster) {
							this.disbandGroup()
						} else {
							this.exitGroup()
						}
					}
				},
			})
		},

		// 退出群聊
		onExitGroup() {
			this.hideGroupActions()
			uni.showModal({
				title: "确认退出",
				content: "确定要退出该群聊吗？",
				confirmText: "退出",
				confirmColor: "#ff4757",
				success: (res) => {
					if (res.confirm) {
						this.exitGroup()
					}
				},
			})
		},

		// 解散群聊
		onDisbandGroup() {
			this.hideGroupActions()
			uni.showModal({
				title: "确认解散",
				content: "确定要解散该群聊吗？解散后无法恢复！",
				confirmText: "解散",
				confirmColor: "#ff4757",
				success: (res) => {
					if (res.confirm) {
						this.disbandGroup()
					}
				},
			})
		},

		// 执行退出群聊
		async exitGroup() {
			try {
				uni.showLoading({
					title: "退出中...",
				})

				// 调用退出群聊接口
				const response = await this.$Request.postApi("/bot/api/agentcoutgroup", { groupid: this.groupid, userid: this.userid, })
				if (response.status === 1) {
					uni.showToast({
						title: "退出成功",
						icon: "none",
					})
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: response.message || "退出失败",
						icon: "none",
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error("退出群聊失败:", error)
				uni.showToast({
					title: "网络错误，请重试",
					icon: "none",
				})
			}
		},

		// 执行解散群聊
		async disbandGroup() {
			try {
				uni.showLoading({
					title: "解散中...",
				})

				// 调用解散群聊接口
				const response = await this.$Request.postApi("/bot/api/agentcalloutgroup", { groupid: this.groupid, userid: this.userid, }
				)

				if (response.status === 1) {
					uni.showToast({
						title: "解散成功",
						icon: "none",
					})
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: response.message || "解散失败",
						icon: "none",
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error("解散群聊失败:", error)
				uni.showToast({
					title: "网络错误，请重试",
					icon: "none",
				})
			}
		},

		// 禁用页面滚动
		disablePageScroll() {
			// 通过CSS类来控制滚动，不需要复杂的JavaScript逻辑
		},

		// 恢复页面滚动
		enablePageScroll() {
			// 通过CSS类来控制滚动，不需要复杂的JavaScript逻辑
		},
		// 检测群组
		checkGroup() {
			return new Promise((resolve) => {
				this.$Request.postApi("/bot/api/agentccheckgroup", { userid: this.userid, friendid: this.friendId }).then(res => {
					if (res && res.data != null && res.data !== undefined) {
						this.groupid = res.data
					}
					resolve(this.groupid)
				}).catch(() => resolve(this.groupid))
			})
		},

		// 初始化录音管理器
		initRecorderManager() {
			// #ifdef APP-PLUS
			try {
				this.recorderManager = uni.getRecorderManager();

				// 监听录音开始事件
				this.recorderManager.onStart(() => {
					// console.log('录音开始');
					// 确保UI状态与录音状态同步
					this.$nextTick(() => {
						this.isRecording = true;
					});
				});

				// 监听录音结束事件
				this.recorderManager.onStop((res) => {
					// console.log('录音结束:', res);
					this.currentAudioPath = res.tempFilePath;

					// 确保UI状态更新 - 增强强制更新机制
					this.isRecording = false;
					this.showRecordingBar = false; // 明确隐藏录音条
					this.showVoiceTip = false;
					this.voiceTipText = "手指上滑，取消发送";

					// 立即强制重置UI
					this.$forceUpdate();

					// 立即发送一个全局事件
					uni.$emit('record-ended');

					// 使用多种方式确保UI更新 - 特别是在Android上
					setTimeout(() => {
						// 重置所有录音相关状态变量
						this.$set(this, 'isRecording', false);
						this.$set(this, 'showRecordingBar', false);

						// 强制再次更新
						this.$forceUpdate();

						// 双重保险：再次确认状态被重置
						setTimeout(() => {
							this.isRecording = false;
							this.showRecordingBar = false;
							this.$forceUpdate();

							// Android特别处理：通过UI刷新
							if (this.isAndroid) {
								// 触发布局刷新
								uni.pageScrollTo({
									scrollTop: 0,
									duration: 1
								});
								// 立即滚回
								setTimeout(() => {
									uni.pageScrollTo({
										scrollTop: 0,
										duration: 1
									});
								}, 10);
							}
						}, 50);
					}, 100);
				});

				// 监听录音错误事件
				this.recorderManager.onError((res) => {
					console.error('录音错误:', res);

					// 发生错误时重置所有状态
					this.$nextTick(() => {
						this.isRecording = false;
						this.showRecordingBar = false; // 明确隐藏录音条
						this.showVoiceTip = false;
						this.willCancelRecord = false;
						this.voiceTipText = "手指上滑，取消发送";
						// 强制更新UI
						this.$forceUpdate();
					});

					uni.showToast({
						title: '录音失败',
						icon: 'none'
					});
				});
			} catch (error) {
				console.error('初始化录音管理器失败:', error);
				uni.showToast({
					title: '录音功能初始化失败',
					icon: 'none'
				});
			}
			// #endif
		},

		// 初始化音频播放器
		initAudioPlayer() {
			try {
				// 先检查是否已经存在音频实例
				if (this.innerAudioContext) {
					try {
						this.innerAudioContext.destroy()
					} catch (destroyError) {
						console.warn('销毁旧音频实例失败:', destroyError)
					}
					this.innerAudioContext = null
				}

				// 创建新的音频实例
				this.innerAudioContext = uni.createInnerAudioContext()

				// 检查音频实例是否创建成功
				if (!this.innerAudioContext) {
					throw new Error('音频实例创建失败')
				}

				// 安全地设置属性，使用更智能的方法
				this.safeSetAudioProperty('autoplay', false)
				this.safeSetAudioProperty('obeyMuteSwitch', true)

				// 绑定事件监听器
				this.innerAudioContext.onEnded(() => {
					this.currentlyPlayingId = null
				})

				this.innerAudioContext.onStop(() => {
					this.currentlyPlayingId = null
				})

				this.innerAudioContext.onError((err) => {
					console.error('音频播放错误:', err)
					this.currentlyPlayingId = null
					uni.showToast({ title: '播放失败', icon: 'none' })
				})

				// console.log('音频播放器初始化成功')
			} catch (e) {
				console.error('创建音频实例失败:', e)
				// 尝试降级处理
				this.fallbackAudioInit()
			}
		},

		// 音频播放器降级初始化
		fallbackAudioInit() {
			try {
				// console.log('尝试降级音频初始化...')

				// 延迟重试
				setTimeout(() => {
					try {
						this.innerAudioContext = uni.createInnerAudioContext()
						if (this.innerAudioContext) {
							// console.log('降级音频初始化成功')
							// 只设置基本的事件监听
							this.innerAudioContext.onEnded(() => {
								this.currentlyPlayingId = null
							})
							this.innerAudioContext.onStop(() => {
								this.currentlyPlayingId = null
							})
							this.innerAudioContext.onError((err) => {
								console.error('音频播放错误:', err)
								this.currentlyPlayingId = null
							})
						}
					} catch (retryError) {
						console.error('降级音频初始化也失败:', retryError)
						uni.showToast({
							title: '音频功能不可用',
							icon: 'none'
						})
					}
				}, 1000)
			} catch (fallbackError) {
				console.error('降级音频初始化失败:', fallbackError)
			}
		},

		// 播放/停止语音
		playVoice(message) {
			// console.log("尝试播放语音消息:", JSON.stringify({
			// 	id: message.id,
			// 	type: message.type,
			// 	audioPath: message.audioPath,
			// 	duration: message.duration
			// }))

			if (!message || !message.audioPath) {
				console.error('语音文件路径缺失:', message)
				uni.showToast({ title: '语音文件不存在', icon: 'none' })
				return
			}

			// 确保音频播放器已初始化
			if (!this.innerAudioContext) {
				this.initAudioPlayer()
				// 如果初始化失败，等待一段时间后重试
				setTimeout(() => {
					if (this.innerAudioContext) {
						this.playVoice(message)
					} else {
						uni.showToast({ title: '音频播放器未就绪', icon: 'none' })
					}
				}, 500)
				return
			}

			// 如果正在播放同一条，点击则停止
			if (this.currentlyPlayingId === message.id) {
				try {
					this.innerAudioContext.stop()
					this.currentlyPlayingId = null
				} catch (stopError) {
					console.error('停止音频播放失败:', stopError)
					this.currentlyPlayingId = null
				}
				return
			}

			// 切换到新的音频
			try {
				// 先停止当前播放
				try {
					this.innerAudioContext.stop()
				} catch (stopError) {
					console.warn('停止当前音频失败:', stopError)
				}

				// console.log("设置音频源:", message.audioPath)

				// 安全地设置音频源
				try {
					this.innerAudioContext.src = message.audioPath
				} catch (srcError) {
					console.error('设置音频源失败:', srcError)
					uni.showToast({ title: '音频源设置失败', icon: 'none' })
					return
				}

				this.currentlyPlayingId = message.id

				// 播放音频
				try {
					this.innerAudioContext.play()
					// console.log('音频开始播放')
				} catch (playError) {
					console.error('音频播放失败:', playError)
					this.currentlyPlayingId = null
					uni.showToast({ title: '播放失败', icon: 'none' })
				}
			} catch (e) {
				console.error('播放语音失败:', e)
				this.currentlyPlayingId = null
				uni.showToast({ title: '播放失败', icon: 'none' })
			}
		},

		// 重置所有录音相关状态
		resetRecordingState() {
			// console.log('重置录音状态被调用')

			// 清除安全定时器
			this.clearRecordingTimer()

			// #ifdef APP-PLUS
			if (this.recorderManager && this.isRecording) {
				try {
					this.recorderManager.stop()
				} catch (error) {
					console.warn('停止录音管理器失败:', error)
				}
			}
			// #endif

			// 立即重置所有相关状态
			this.isRecording = false
			this.showRecordingBar = false
			this.showVoiceTip = false
			this.willCancelRecord = false
			this.voiceTipText = "手指上滑，取消发送"

			// 立即强制更新UI状态
			this.$forceUpdate()

			// 尝试使用uni选择器 (Android兼容性处理)
			setTimeout(() => {
				try {
					// 使用uni选择器代替document
					const query = uni.createSelectorQuery();
					query.selectAll('.recording-bar-outer').fields({
						rect: true,
						size: true
					}, data => {
						// console.log('找到录音条元素:', data);
					}).exec();
				} catch (e) {
					// console.log('选择器API失败', e);
				}

				// 强制再次更新状态
				this.isRecording = false
				this.showRecordingBar = false
				this.$forceUpdate()
			}, 10);

			// 双重保险：100ms后再次更新状态 (Android兼容性)
			setTimeout(() => {
				this.isRecording = false
				this.showRecordingBar = false
				this.$forceUpdate()
			}, 100)
		},

		// 清除录音安全定时器
		clearRecordingTimer() {
			if (this.recordingTimer) {
				clearTimeout(this.recordingTimer)
				this.recordingTimer = null
			}
		},



		// 安全地设置音频属性
		safeSetAudioProperty(propertyName, value) {
			try {
				// 检查属性是否存在
				if (!(propertyName in this.innerAudioContext)) {
					// console.log(`属性 ${propertyName} 不存在，跳过设置`)
					return
				}

				// 获取属性描述符
				const descriptor = Object.getOwnPropertyDescriptor(this.innerAudioContext, propertyName)

				if (descriptor) {
					// 如果属性是只读的，跳过设置
					if (descriptor.writable === false) {
						// console.log(`属性 ${propertyName} 是只读的，跳过设置`)
						return
					}

					// 如果属性不可配置，跳过设置
					if (descriptor.configurable === false) {
						// console.log(`属性 ${propertyName} 不可配置，跳过设置`)
						return
					}
				}

				// 尝试直接设置属性值
				this.innerAudioContext[propertyName] = value

			} catch (error) {
				// 不显示警告，因为这是预期的行为
			}
		},

		// 预览图片
		previewImage(imageUrl) {
			this.previewImageUrl = imageUrl;
			this.showImagePreview = true;
		},

		// 关闭图片预览
		closeImagePreview() {
			this.showImagePreview = false;
		},

		// ========== 消息轮询相关方法 ==========

		// 启动消息轮询
		startMessagePolling() {
			// 先停止可能存在的轮询
			this.stopMessagePolling();

			// 保存最后一条消息ID，用于后续比较
			if (this.chatMessages && this.chatMessages.length > 0) {
				this.lastMessageId = this.chatMessages[this.chatMessages.length - 1].id;
			}

			// 启动新的轮询
			this.pollTimer = setInterval(() => {
				this.pollNewMessages();
			}, this.pollInterval);
		},

		// 停止消息轮询
		stopMessagePolling() {
			if (this.pollTimer) {
				clearInterval(this.pollTimer);
				this.pollTimer = null;
			}
		},

		// 轮询获取新消息
		async pollNewMessages() {
			try {
				// 空值保护
				if (!this.userid || !this.groupid) {
					return;
				}

				// 调用接口获取最新消息 	
				// 可以添加一个时间戳参数，避免缓存
				// timestamp: Date.now()
				const response = await this.$Request.postApi('/bot/api/agentcgetimmessage', {
					userid: this.userid,
					groupid: this.groupid,

				});

				if (response && response.status === 1 && Array.isArray(response.data)) {
					// 检查是否有新消息
					if (response.data.length > 0) {
						// 找到最新的消息ID
						const latestMessages = response.data.sort((a, b) =>
							(this.normalizeTimestamp(b.create_time) - this.normalizeTimestamp(a.create_time))
						);

						// 检查是否有新消息
						if (latestMessages.length > 0 &&
							(!this.lastMessageId ||
								latestMessages[0].id !== this.lastMessageId)) {

							// 将接口数据映射到现有消息结构
							const mapped = response.data
								.sort((a, b) => (this.normalizeTimestamp(a.create_time) - this.normalizeTimestamp(b.create_time)))
								.map(item => this.formatMessageFromApi(item));

							// 更新消息列表
							this.chatMessages = mapped;

							// 更新最后一条消息ID
							if (this.chatMessages.length > 0) {
								this.lastMessageId = this.chatMessages[this.chatMessages.length - 1].id;

								// 如果用户没有在滚动，则滚动到底部
								this.$nextTick(() => {
									this.scrollToBottom();
								});
							}
						}
					}
				}
			} catch (error) {
				console.error('轮询获取消息失败:', error);
				// 出错时不停止轮询，让它继续尝试
			}
		},
	},
}
</script>

<style>
page {
	background: #100d05;
}
</style>

<style lang="scss" scoped>
.chat-page {
	width: 100%;
	height: 100vh;
	background: #100d05;
	position: relative;
	overflow: hidden;
}

// 顶部导航
.status-bar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background: #100d05;
	display: flex;
	align-items: center;
	color: #333;
	font-weight: 500;
	font-size: 35rpx;
	color: #fff;

	.nav-bar {
		display: flex;
		align-items: center;
		width: 100%;

		.nav-bar-left {
			display: flex;
			align-items: center;
			margin-left: 32rpx;

			.nav-back-icon {
				width: 46.15rpx;
				height: 46.15rpx;
			}
		}

		.nav-bar-title {
			flex: 1;
			text-align: center;
			font-size: 35rpx;
			font-weight: 600;
			color: #fff;
		}

		.nav-bar-right {
			width: 60rpx;
		}
	}
}

.status-height-color {
	background: #100d05;
}

// 聊天内容区域
.chat-content {
	width: 100%;
	// background: #100D05;
	padding: 20rpx 0 60rpx 0;
	box-sizing: border-box;
}

.chat-messages {
	padding: 0 20rpx;
}

// 时间分割线
.time-divider {
	text-align: center;
	margin: 30rpx 0;

	.time-text {
		background: rgba(0, 0, 0, 0.1);
		color: #999;
		font-size: 24rpx;
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
	}
}

// 消息项
.message-item {
	margin-bottom: 30rpx;

	&.message-mine {
		.message-content {
			flex-direction: row-reverse;

			.message-bubble {
				background-color: #a9ea7a;
				margin-right: 20rpx;
				margin-left: 80rpx;
				border-radius: 20rpx 20rpx 4rpx 20rpx;

				// 如果是图片消息，移除背景和边框
				&.message-image-type {
					background-color: transparent;
					border: none;
					padding: 0; // 图片本身通常不需要内边距
				}
			}
		}
	}

	&.message-other {
		.message-content {
			flex-direction: row;

			.message-bubble {
				background: #fff;
				margin-left: 20rpx;
				margin-right: 80rpx;
				border-radius: 20rpx 20rpx 20rpx 4rpx;
				border: 1rpx solid #e5e5e5;

				// 如果是图片消息，移除背景和边框
				&.message-image-type {
					background-color: transparent;
					border: none;
					padding: 0; // 图片本身通常不需要内边距
				}
			}
		}
	}
}

.message-content {
	display: flex;
	align-items: flex-start;
}

.message-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	overflow: hidden;
	flex-shrink: 0;

	.avatar-img {
		width: 80rpx;
		height: 80rpx;
	}
}

.message-bubble {
	max-width: 60%;
	padding: 20rpx;
	word-wrap: break-word;

	.message-text {
		font-size: 28rpx;
		color: #333;
		line-height: 1.4;
	}

	.message-emoji {
		font-size: 40rpx;
		line-height: 1;
	}

	.message-image {
		.image-content {
			max-width: 240rpx; // 限制最大宽度，让图片更小
			max-height: 360rpx; // 限制最大高度
			border-radius: 8rpx;
			object-fit: contain; // 保持图片完整显示，不裁剪
		}

		// border-radius: 20rpx; // 添加圆角
		// overflow: hidden; // 隐藏超出圆角部分
	}

	.message-voice {
		.voice-content {
			display: flex;
			align-items: center;
			justify-content: center;
			min-width: 120rpx;

			.voice-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}

			.voice-duration {
				font-size: 24rpx;
				color: #666;
			}
		}
	}
}

// 加载更多
.loading-more {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 40rpx 0;

	.loading-spinner {
		width: 40rpx;
		height: 40rpx;
		border: 3rpx solid rgba(0, 0, 0, 0.1);
		border-top: 3rpx solid #007aff;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	.loading-text {
		font-size: 24rpx;
		color: #999;
	}
}

// 无消息提示
.empty-messages {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 200rpx 0;

	.empty-img {
		width: 180rpx;
		height: 120rpx;
		margin-bottom: 40rpx;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
}

// 底部输入区域
.input-area {
	position: fixed;
	left: 0;
	right: 0;
	// background: #fff;
	background: #100d05;
	// border-top: 1rpx solid #e5e5e5;
	border-top: 1rpx solid #100d05;

	padding: 20rpx;
	padding-bottom: 20rpx;
	box-sizing: border-box;
	z-index: 998;
}

.input-container {
	display: flex;
	align-items: center;
	// background: #f5f5f5;
	background: rgba(130, 128, 128, 0.5);
	border-radius: 16rpx;
	// padding: 10rpx;
	padding: 12rpx 10rpx;
	gap: 20rpx;
	margin: 0 20rpx;
}

.input-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;

	.btn-icon {
		width: 46rpx;
		height: 46rpx;
	}

	.btn-icon1 {
		width: 54rpx;
		height: 54rpx;
	}
}

.input-center {
	flex: 1;
	display: flex;
	align-items: center;
}

.text-input-wrapper {
	width: 100%;

	.text-input {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 28rpx;
		color: #ffffff;
		background: transparent;
		border: none;
		outline: none;

		&::placeholder {
			color: #ffffff;
		}
	}
}

.input-right-buttons {
	display: flex;
	align-items: center;
	gap: 10rpx;
	flex-shrink: 0;
}

.voice-input-wrapper {
	width: 100%;

	.voice-input-btn {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		// background: #007aff;
		color: #fff;
		text-align: center;
		border-radius: 30rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.2s ease;
		// 防止触摸滚动
		touch-action: none;
		-webkit-touch-callout: none;
		-webkit-user-select: none;
		user-select: none;

		&:active {
			// background: #0056b3;
			transform: scale(0.98);
		}

		.voice-input-text {
			color: #fff;
			font-size: 32rpx;
			padding-left: 50rpx;

			&.voice-hidden {
				display: none;
				opacity: 0;
				visibility: hidden;
			}
		}
	}
}

.send-btn {
	margin-left: 20rpx;
	background: #007aff;
	color: #fff;
	padding: 20rpx 30rpx;
	border-radius: 30rpx;
	flex-shrink: 0;

	.send-text {
		font-size: 28rpx;
	}

	&:active {
		background: #0056b3;
	}
}

// 表情面板
.emoji-panel {
	position: fixed;
	left: 0;
	right: 0;
	background: #fff;
	border-top: 1rpx solid #e5e5e5;
	z-index: 997;
	height: 400rpx;
}

.emoji-content {
	height: 100%;
	padding: 20rpx;
	box-sizing: border-box;
}

.emoji-scroll {
	height: 100%;
	-webkit-overflow-scrolling: touch;
}

.emoji-grid {
	display: grid;
	grid-template-columns: repeat(8, 1fr);
	gap: 15rpx;
	padding: 20rpx;
	padding-bottom: 40rpx;
}

.emoji-item {
	width: 70rpx;
	height: 70rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 45rpx;
	background: #f8f8f8;
	border-radius: 12rpx;
	transition: all 0.2s ease;
	cursor: pointer;

	&:active {
		background: #e8e8e8;
		transform: scale(0.9);
	}

	&:hover {
		background: #f0f0f0;
	}
}

// 更多功能面板
.more-panel {
	position: fixed;
	left: 0;
	right: 0;
	background: #100d05;
	border-top: 1rpx solid #e5e5e5;
	z-index: 997;
}

.more-content {
	padding: 50rpx 20rpx;
}

.more-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 40rpx;
}

.more-item {
	display: flex;
	flex-direction: column;
	align-items: center;

	.more-icon-bg {
		width: 102rpx;
		height: 102rpx;
		margin-bottom: 15rpx;
		background: rgba(130, 128, 128, 0.5);
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.more-icon {
			width: 60rpx;
			height: 60rpx;
		}
	}


	.more-text {
		font-size: 24rpx;
		color: #fff;
	}
}

// 录音提示
.voice-record-tip {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	background: rgba(0, 0, 0, 0.8);
	border-radius: 20rpx;
	padding: 40rpx;
	z-index: 1000;
	// 防止触摸滚动
	touch-action: none;
	-webkit-touch-callout: none;
	-webkit-user-select: none;
	user-select: none;
	pointer-events: none; // 防止触摸事件穿透
}

.voice-tip-content {
	display: flex;
	flex-direction: column;
	align-items: center;

	.voice-tip-icon {
		width: 100rpx;
		height: 100rpx;
		margin-bottom: 20rpx;
	}

	.voice-tip-text {
		color: #fff;
		font-size: 28rpx;
	}
}

// 录音条样式
.recording-bar-outer {
	width: 100%;
	height: 85rpx;
	border-radius: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	/* 默认隐藏 */
	display: none;
	opacity: 0;
	visibility: hidden;
	/* 添加过渡效果，帮助Android渲染 */
	transition: opacity 0.05s ease, visibility 0.05s ease;
	will-change: opacity, visibility, display;
	transform: translateZ(0);

	/* 显示时的样式 */
	&.recording-visible {
		display: flex !important;
		opacity: 1 !important;
		visibility: visible !important;
	}

	&.recording-hidden {
		display: none !important;
		opacity: 0 !important;
		visibility: hidden !important;
	}

	/* Android兼容性：强制添加可见性控制 */
	&[v-show="false"],
	&.hidden {
		display: none !important;
		visibility: hidden !important;
		opacity: 0 !important;
	}
}

.recording-bar-inner {
	width: 240rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: transparent;
}

.recording-bar {
	width: 180rpx;
	height: 36rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8rpx;

	.bar {
		width: 8rpx;
		background: #fff;
		border-radius: 4rpx;
		height: 24rpx; // 默认高度
		transform-origin: center bottom; // 从底部中心缩放

		// 使用CSS动画，性能更好
		animation: barWave 1.5s ease-in-out infinite;
		animation-delay: var(--delay); // 每个bar有不同的延迟
		animation-play-state: paused; // 默认暂停

		// 添加硬件加速
		will-change: transform, height;
		backface-visibility: hidden;
		perspective: 1000px;
	}

	// 当录音时启动动画
	&.animating .bar {
		animation-play-state: running;
	}
}

// 音频条波动动画
@keyframes barWave {

	0%,
	100% {
		height: 24rpx;
		transform: scaleY(1);
		opacity: 0.8;
	}

	25% {
		height: 40rpx;
		transform: scaleY(1.2);
		opacity: 1;
	}

	50% {
		height: 32rpx;
		transform: scaleY(1.1);
		opacity: 0.9;
	}

	75% {
		height: 48rpx;
		transform: scaleY(1.3);
		opacity: 1;
	}
}

// 为不同位置的bar添加不同的动画效果
.recording-bar .bar:nth-child(odd) {
	animation-duration: 1.2s; // 奇数bar稍快
}

.recording-bar .bar:nth-child(even) {
	animation-duration: 1.8s; // 偶数bar稍慢
}

// 添加渐变效果，让动画更自然
.recording-bar .bar {
	background: linear-gradient(to top, #fff, #e0e0e0);
	box-shadow: 0 0 8rpx rgba(255, 255, 255, 0.3);
}

// 录音时禁用页面滚动
.recording-active {
	.chat-content {
		overflow: hidden !important;
		touch-action: none !important;
	}

	.chat-page {
		overflow: hidden !important;
		touch-action: none !important;
	}
}

// 动画
@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

// 适配不同平台
/* #ifdef APP-PLUS */
.input-area {
	padding-bottom: 40rpx;
}

.chat-content {
	-webkit-overflow-scrolling: touch;
	overscroll-behavior: contain;
}

.emoji-scroll {
	-webkit-overflow-scrolling: touch;
	overscroll-behavior: contain;
}

/* #endif */

/* #ifdef MP-WEIXIN */
.input-area {
	padding-bottom: 20rpx;
}

/* #endif */

/* #ifdef H5 */
.input-area {
	padding-bottom: 20rpx;
}

/* #endif */

// iOS和Android特定样式
.ios-safe-area {
	padding-bottom: env(safe-area-inset-bottom);
}

.android-safe-area {
	padding-bottom: 0;
}

// 调试信息样式
.debug-info {
	position: fixed;
	top: 100rpx;
	right: 20rpx;
	background: rgba(0, 0, 0, 0.8);
	color: #fff;
	padding: 20rpx;
	border-radius: 10rpx;
	font-size: 24rpx;
	z-index: 1001;

	text {
		display: block;
		margin-bottom: 10rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}
}

// 群聊操作弹窗样式
.group-actions-content {
	height: 100%;
	display: flex;
	flex-direction: column;
	background: #fff;
}

.popup-content {
	flex: 1;
	overflow-y: auto;
	// padding-top: 20rpx;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	// padding: 0 30rpx 30rpx;
	padding: 0 30rpx 0rpx;
	border-bottom: 1rpx solid #f0f0f0;
	position: relative;

	.safe-area-top {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: env(safe-area-inset-top);
		background: #fff;
	}

	.header-content {
		position: relative;
		width: 100%;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.popup-title {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		white-space: nowrap;
		z-index: 1;
	}

	.close-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: auto;
		margin-top: 1px;


		.close-icon {
			width: 40rpx;
			height: 40rpx;
		}
	}
}

.actions-list {
	flex: 1;
}

.action-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1rpx solid #f8f8f8;
	transition: background-color 0.2s ease;

	&:active {
		background-color: #f5f5f5;
	}

	&:last-child {
		border-bottom: none;
	}

	.action-left {
		display: flex;
		align-items: center;

		.action-icon {
			width: 48rpx;
			height: 48rpx;
			margin-right: 20rpx;
		}

		.action-text {
			font-size: 32rpx;
			color: #333;
			font-weight: 500;
		}
	}

	.arrow-icon {
		width: 32rpx;
		height: 32rpx;
		opacity: 0.6;
	}

	.member-count {
		font-size: 28rpx;
		color: #666;
		font-weight: 400;
	}
}

// 群聊成员列表样式
.members-section {
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #f8f8f8;
}

.members-grid {
	display: grid;
	grid-template-columns: repeat(5, 1fr);
	gap: 20rpx;
}

.member-item {
	display: flex;
	flex-direction: column;
	align-items: center;

	.member-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		overflow: hidden;
		margin-bottom: 12rpx;
		background: #f5f5f5;

		.avatar-img {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}

	.member-name {
		font-size: 24rpx;
		color: #333;
		text-align: center;
		line-height: 1.2;
		max-width: 90rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}

// 底部按钮区域样式
.bottom-buttons {
	padding: 30rpx;
	border-top: 1rpx solid #f0f0f0;
	background: #fff;
	flex-shrink: 0;
}

.action-button {
	width: 100%;
	height: 88rpx;
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 20rpx;
	transition: all 0.2s ease;

	&:last-child {
		margin-bottom: 0;
	}

	&:active {
		transform: scale(0.98);
	}

	.button-text {
		font-size: 32rpx;
		font-weight: 500;
	}
}

.exit-button {
	background: #ff4757;
	color: #fff;

	.button-text {
		color: #fff;
	}

	&:active {
		background: #ff5252;
	}
}

.disband-button {
	background: #ff4757;
	color: #fff;

	.button-text {
		color: #fff;
	}

	&:active {
		background: #ff3742;
	}
}

// 适配不同平台
/* #ifdef APP-PLUS */
.group-actions-content {
	padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
	.safe-area-top {
		height: var(--status-bar-height);
	}
}

/* #endif */

/* #ifdef MP-WEIXIN */
.group-actions-content {
	padding-bottom: 20rpx;
}

.popup-header {
	.safe-area-top {
		height: 44px;
	}
}

/* #endif */

/* #ifdef H5 */
.group-actions-content {
	padding-bottom: 20rpx;
}

.popup-header {
	.safe-area-top {
		height: 0;
	}
}

/* #endif */

// 图片预览样式
.image-preview {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: #100d05;
	z-index: 1001;
	display: flex;
	align-items: center;
	justify-content: center;

	.preview-image {
		width: 100%;
		height: 100%;
	}
}
</style>